package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 桑基图
 *
 * @author chart
 */
@RestController
@RequestMapping("/sankey/chart")
public class SankeyChartController extends BaseController {


    @Autowired
    private IChartConfigsService chartConfigsService;

    /**
     * 桑基图
     * 垂直桑基图
     * @param chartDateTto
     * @return
     * @throws Exception
     */
    @PostMapping("/importData1")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        if (chartDateTto.getChartValue() != null) {
            if (chartDateTto.getConfigId() == 36 || chartDateTto.getConfigId() == 70) {

                // 转换数据列表为工作表
                Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());
                List<List<String>> getdata = ExcelDataUtils.getData(sheet);
                if (CollectionUtils.isEmpty(getdata)) {
                    return AjaxResult.error("请填充数据");
                }

                // 检查唯一数据类别
                Set<String> xlist = new HashSet<>();
                List<List<Object>> dataList = new ArrayList<>();
                for (int i = 1; i < getdata.size(); i++) {
                    List<String> list = getdata.get(i);
                    if (!CollectionUtils.isEmpty(list)) {
                        List<Object> newList = new ArrayList<>();
                        for (int i1 = 0; i1 < list.size(); i1++) {
                            String s = list.get(i1);
                            if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                                if (i1 == 0 || i1 == 1) {
                                    xlist.add(s);
                                }
                                newList.add(s);
                            }
                        }
                        dataList.add(newList);
                    }
                }

                // 解析图表配置 JSON
                JSONObject jsonObject = JSON.parseObject(chartDateTto.getChartValue());
                if (jsonObject == null) {
                    return AjaxResult.error("无效的图表值 JSON");
                }

                // 访问 series 数组
                JSONArray seriesArray = jsonObject.getJSONArray("series");
                if (seriesArray == null || seriesArray.isEmpty()) {
                    return AjaxResult.error("JSON 中未找到或为空的 series 键");
                }

                // 获取第一个 series 对象
                JSONObject series = seriesArray.getJSONObject(0);
                if (series == null) {
                    return AjaxResult.error("JSON 中未找到 series 对象");
                }

                // 更新 series 中的 data
                List<Map<String, String>> maps = new ArrayList<>();
                for (String name : xlist) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", name);
                    maps.add(map);
                }
                series.put("data", maps);

                // 更新 series 中的 links
                List<JSONObject> links = series.getJSONArray("links").toJavaList(JSONObject.class);
                if (links == null || links.isEmpty()) {
                    return AjaxResult.error("JSON 中未找到或为空的 links 键");
                }

                JSONObject jsonObject1 = links.get(0);
                List<JSONObject> linkList = new ArrayList<>();
                for (List<Object> list : dataList) {
                    JSONObject jsonObject2 = new JSONObject(jsonObject1);
                    jsonObject2.put("source", list.get(0));
                    jsonObject2.put("target", list.get(1));
                    jsonObject2.put("value", list.get(2));
                    linkList.add(jsonObject2);
                }
                series.put("links", linkList);

                // 更新 JSON 对象中的 series
                seriesArray.set(0, series);
                jsonObject.put("series", seriesArray);

                // 创建并返回结果
                ArrayList<ChartSmartVo> newList = new ArrayList<>();
                ChartSmartVo chartsVo = new ChartSmartVo();
                chartsVo.setConfigValue(JSON.toJSONString(jsonObject));
                newList.add(chartsVo);
                return AjaxResult.success(newList);

            }

        } else {
            if (chartDateTto.getConfigId() == 36 || chartDateTto.getConfigId() == 70) {
                Integer id = chartDateTto.getConfigId();
                ChartConfigs chartConfigs = chartConfigsService.getById(id);
                String configValue = chartConfigs.getConfigValue();
                // 转换数据列表为工作表
                Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());
                List<List<String>> getdata = ExcelDataUtils.getData(sheet);
                if (CollectionUtils.isEmpty(getdata)) {
                    return AjaxResult.error("请填充数据");
                }

                // 检查唯一数据类别
                Set<String> xlist = new HashSet<>();
                List<List<Object>> dataList = new ArrayList<>();
                for (int i = 1; i < getdata.size(); i++) {
                    List<String> list = getdata.get(i);
                    if (!CollectionUtils.isEmpty(list)) {
                        List<Object> newList = new ArrayList<>();
                        for (int i1 = 0; i1 < list.size(); i1++) {
                            String s = list.get(i1);
                            if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                                if (i1 == 0 || i1 == 1) {
                                    xlist.add(s);
                                }
                                newList.add(s);
                            }
                        }
                        dataList.add(newList);
                    }
                }

                // 解析图表配置 JSON
                JSONObject jsonObject = JSON.parseObject(configValue);
                if (jsonObject == null) {
                    return AjaxResult.error("无效的图表值 JSON");
                }

                // 访问 series 数组
                JSONArray seriesArray = jsonObject.getJSONArray("series");
                if (seriesArray == null || seriesArray.isEmpty()) {
                    return AjaxResult.error("JSON 中未找到或为空的 series 键");
                }

                // 获取第一个 series 对象
                JSONObject series = seriesArray.getJSONObject(0);
                if (series == null) {
                    return AjaxResult.error("JSON 中未找到 series 对象");
                }

                // 更新 series 中的 data
                List<Map<String, String>> maps = new ArrayList<>();
                for (String name : xlist) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", name);
                    maps.add(map);
                }
                series.put("data", maps);

                // 更新 series 中的 links
                List<JSONObject> links = series.getJSONArray("links").toJavaList(JSONObject.class);
                if (links == null || links.isEmpty()) {
                    return AjaxResult.error("JSON 中未找到或为空的 links 键");
                }

                JSONObject jsonObject1 = links.get(0);
                List<JSONObject> linkList = new ArrayList<>();
                for (List<Object> list : dataList) {
                    JSONObject jsonObject2 = new JSONObject(jsonObject1);
                    jsonObject2.put("source", list.get(0));
                    jsonObject2.put("target", list.get(1));
                    jsonObject2.put("value", list.get(2));
                    linkList.add(jsonObject2);
                }
                series.put("links", linkList);

                // 更新 JSON 对象中的 series
                seriesArray.set(0, series);
                jsonObject.put("series", seriesArray);

                // 创建并返回结果
                ArrayList<ChartSmartVo> newList = new ArrayList<>();
                ChartSmartVo chartsVo = new ChartSmartVo();
                chartsVo.setConfigValue(JSON.toJSONString(jsonObject));
                newList.add(chartsVo);
                return AjaxResult.success(newList);

            }


        }


        return null;
    }


    @PostMapping("v2/importData1")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists, Long configId) throws Exception {

        // XSSFWorkbook workbook = null;
        try {
            // Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            Sheet sheet = ExcelUtils.convertDataListToSheets(dataLists);
      /*      workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            System.out.println(getdata);
            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }


            //数据的种类不能重复
            Set<String> xlist = new HashSet<>();
            List<List<Object>> dataList = new ArrayList<>();
            for (int i = 1; i < getdata.size(); i++) {
                List<String> list = getdata.get(i);
                if (!CollectionUtils.isEmpty(list)) {
                    List<Object> newList = new ArrayList<>();
                    for (int i1 = 0; i1 < list.size(); i1++) {
                        String s = list.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            if (i1 == 0 || i1 == 1) {
                                xlist.add(s);
                            }
                            newList.add(s);
                        }
                    }
                    dataList.add(newList);
                }
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            List<Map> maps = new ArrayList<>();
            JSONObject series = (JSONObject) jsonObject.get("series");

            Iterator<String> iterator = xlist.iterator();
            while (iterator.hasNext()) {
                Map map = new HashMap<>();
                map.put("name", iterator.next());
                maps.add(map);
            }

            series.put("data", maps);

            List<JSONObject> links = (List<JSONObject>) series.get("links");
            JSONObject jsonObject1 = links.get(0);

            List<JSONObject> linkList = new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                List<Object> list = dataList.get(i);

                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.putAll(jsonObject1);

                jsonObject2.put("source", list.get(0));
                jsonObject2.put("target", list.get(1));
                jsonObject2.put("value", list.get(2));

                linkList.add(jsonObject2);
            }
            series.put("links", linkList);

            jsonObject.put("series", series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            //workbook.close();
        }
    }
}
